#!groovy
@Library("jenkinslib") _

//func from sharelibrary调用共享库
def build=new org.devops.build()
def k8s=new org.devops.k8s()
def k8sdeploy=new org.devops.k8sdeploy()
def tools=new org.devops.tools()
def harbor=new org.devops.Harbor()
def toemail=new org.devops.toemail()
def template=new org.devops.template()
//调用Jenkins中定义的选项参数 名称和Jenkins中定义的保持一致
//from jenkins 参数化构建变量
String Tenv="${env.Tenv}"
String buildType="${env.buildType}"
String buildshell="${env.buildshell}"
String srcURL="${env.SrcURL}"
String branch="${env.branchName}"
String k8s_ns="${env.k8s_ns}"
String controllerType="${env.controllerType}"
String imageName="${env.imageName}"
String imageTag="${env.imageTag}" 
String replicas="${env.replicas}"
String containerPort="${env.ContainerPort}"
Boolean rollback = (env.rollback == 'true')
Boolean isPublish = (env.isPublish == 'true')
String deployMethod = "${env.deployMethod}" ?: "kubectl"
String waitMins = "${env.waitMins}" ?: "60"

// 固定配置
env.HARBOR_URL = "harbor.jdicity.local"
env.PROJECT_GROUP = "registry"
def currentStage = ''
pipeline{
    agent {
        kubernetes { 
            cloud 'kubernetes'              // 对应 Jenkins 中配置的 Kubernetes 云名称
            inheritFrom 'jenkins-slave'  // 继承的 Pod 模板（可选）
            namespace 'default'      // 命名空间
            yaml k8s()            // 调用共享库生成 Pod YAML
        }
    }
    options {
        timestamps()
        skipDefaultCheckout()  // 禁用隐式 Checkout
        timeout(time: 1, unit: 'HOURS') //设置流水线超时
    }
    stages{
        stage("CheckOut"){
            when { expression { !rollback } }  // 非回滚时执行
            steps{
                script{
                    tools.PrintMsg("获取分支: ${branch}","checkout")
                    tools.PrintMsg("获取代码","checkout")
                    checkout([$class: 'GitSCM', branches: [[name: "${branch}"]], 
                        extensions: [], 
                        userRemoteConfigs: [[credentialsId: 'gitee_registry_ssh', url: "${srcURL}"]]])
                }
            }
        }
        stage("Build"){
            when { expression { !rollback } }  // 非回滚时执行
            steps{
                script{
                    //集成构建工具
                    container('mvn') {
                        tools.PrintMsg("代码编译","build")
                        build.Build(buildType,buildshell)
                    }
                }
            }
        }
        stage("镜像tag"){
            when { expression { !rollback } }  // 非回滚时执行
            steps{
                script{
                    tools.PrintMsg("获取镜像tag","image_tag")
                    // 使用 Jenkins 主机的本地时间（绕过容器时钟问题）
                    TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"))
                    env.BUILD_TIME = new Date().format("yyyyMMdd_HHmmss")
                        // 组合完整Tag
                    env.FULL_IMAGE_TAG = "${imageTag}"+"_"+"${Tenv}"+"_"+env.BUILD_TIME
                    env.FULL_IMAGE_NAME="${env.HARBOR_URL}/${env.PROJECT_GROUP}/${imageName}:${env.FULL_IMAGE_TAG}"
                    tools.PrintMsg("生成镜像Tag: ${FULL_IMAGE_TAG}", "image_tag")
                    tools.PrintMsg("生成镜像地址: ${FULL_IMAGE_NAME}", "image_tag")
                   
                }    
            }
        }
        stage("镜像构建"){
            when { expression { !rollback } }  // 非回滚时执行
            steps{
                script{
                    container('docker') {
                        currentStage = '镜像构建'
                        tools.PrintMsg("代码打包","image_build")
                        harbor.BuildImage(
                        this,
                        'HARBOR_ID',
                        env.HARBOR_URL,
                        env.PROJECT_GROUP,
                        "${imageName}",
                        env.FULL_IMAGE_TAG)
                        
                        // 镜像构建完成后立即发送邮件
                        toemail.Email(
                            "SUCCESS",
                            "${env.emailUser}",
                            "${imageName}",
                            "${branch}",
                            "${env.BUILD_USER}",
                            env.BUILD_TIME,
                            currentBuild.durationString ?: "N/A",
                            false,
                            "${k8s_ns}",
                            "CI阶段完成 - 镜像: ${env.FULL_IMAGE_NAME}",
                            "${srcURL}",
                            true
                        )
                    }
                }
            }
        }
        stage("生成部署模板") {
            when { 
                allOf {
                    expression { !rollback } 
                    expression {deployMethod == 'kubectl'}
                }
            }   
            steps {
                container('kubectl') {
                    script {
                        tools.PrintMsg("并行生成部署模板","template")
                            // 并行生成不同类型的模板
                        parallel(
                            "生成${controllerType}模板": {
                                template.generateDeploymentTemplate(
                                    this,
                                    "${controllerType}",
                                    "${imageName}",
                                    "${replicas}",
                                    env.FULL_IMAGE_NAME,
                                    "${containerPort}",
                                    "${k8s_ns}"
                                )
                            },
                            "生成Service模板": {
                                template.generateServiceTemplate(
                                    this,
                                    "${imageName}",
                                    "${containerPort}",
                                    "${k8s_ns}"
                                )
                            },
                            failFast: true
                        )
                    }
                }
            }
        }
        stage("部署到k8s"){
            when { 
                allOf{
                    expression { !rollback }
                    expression { isPublish }
                    }
                }
            steps{
                script{
                    if (deployMethod == "helm") {
                        container('helm') {
                            currentStage = '部署到k8s集群'
                            tools.PrintMsg("部署到${Tenv}环境","deploy")
                            // 检查helm目录是否存在
                            if (!fileExists("${WORKSPACE}/helm/Chart.yaml")) {
                                error "🚨 Helm Chart目录不存在或Chart.yaml文件缺失"
                            }
                            // Helm部署逻辑
                            // def chartName = "${imageName}-chart"
                            def releaseName = "${imageName}-${Tenv}"
                                    // 打包Chart
                            dir("${WORKSPACE}/helm") {
                                        // 动态更新Chart版本（示例：使用构建号）
                                sh "sed -i 's/version: .*/version: ${BUILD_NUMBER}/' Chart.yaml"
                                sh "/usr/local/bin/helm package . -d ${WORKSPACE}/ --version ${BUILD_NUMBER}"
                                        // sh "/usr/local/bin/helm repo add myrepo https://harbor.jdicity.local/chartrepo --username admin --password 'nRt87ccD&H*T%4WG' --ca-file /app/harbor.jdicity.local.crt"
                                        // sh "helm cm-push ${WORKSPACE}/${imageName}-${BUILD_NUMBER}.tgz myrepo --ca-file /usr/local/harbor.jdicity.local.crt"
                                          // 添加带认证的Helm仓库
                                withCredentials([usernamePassword(
                                    credentialsId: 'HARBOR_ID', 
                                    usernameVariable: 'HARBOR_USER', 
                                    passwordVariable: 'HARBOR_PASSWORD'
                                )]) {
                                    sh "helm repo remove ${releaseName} || true"
                                    sh """
                                        helm repo add ${releaseName} https://harbor.jdicity.local/chartrepo/myrepo --ca-file /usr/local/harbor.jdicity.local.crt \
                                            --username ${HARBOR_USER} \
                                            --password '${HARBOR_PASSWORD.replace("'", "'\\''")}' 
                                                
                                        helm cm-push ${WORKSPACE}/${imageName}-${BUILD_NUMBER}.tgz ${releaseName} \
                                            --ca-file /usr/local/harbor.jdicity.local.crt \
                                            --username ${HARBOR_USER} \
                                            --password '${HARBOR_PASSWORD.replace("'", "'\\''")}'
                                    """
                                }
                            }

                            
                            // 部署Chart
                            k8sdeploy.HelmDeploy(
                                this,
                                "${Tenv}",
                                "${releaseName}",
                                "${releaseName}/${imageName}",
                                "${k8s_ns}",
                                [
                                    "image.repository": "${env.FULL_IMAGE_NAME}",
                                    "replicas": "${replicas}",
                                    "containerPort": "${containerPort}"
                                ],
                                "${BUILD_NUMBER}" 
                            )
                        }
                    } else {
                        container('kubectl') {  // 这里应该使用kubectl容器
                            tools.PrintMsg("部署到${Tenv}环境","deploy")
                            currentStage = '部署到k8s集群'
                            // 原有kubectl部署逻辑
                            k8sdeploy.Deploy(
                                this,
                                "${Tenv}",
                                "${controllerType}",
                                "${imageName}",
                                "${env.FULL_IMAGE_NAME}",
                                "${k8s_ns}"
                            )
                        }
                    }
                    // 保存镜像信息
                    env.FULL_IMAGE_NAME = "${env.FULL_IMAGE_NAME}"
                    currentBuild.description = "${env.FULL_IMAGE_NAME}"
                }
            }
        }
        // 新增手动发布阶段
        stage("手动发布"){
            when { 
                allOf {
                    expression { !rollback }
                    expression { !isPublish }
                }
            }
            steps {
                script {
                    timeout(time: waitMins.toInteger(), unit: 'MINUTES') {
                        // echo "DEBUG - isPublish值: ${isPublish}"
                        // 修改input处理方式，直接检查返回值是否为null
                        def approval = input(
                            message: "确认要发布到${Tenv}环境吗？(等待时间: ${waitMins}分钟)", 
                            ok: "确认发布"
                        )
                        
                        // echo "DEBUG - 确认发布结果: ${approval}"
                        
                        // 只要用户点击确认就执行发布
                        if (approval == null) {
                            // 复用原有部署逻辑
                            if (deployMethod == "helm") {
                                container('helm') {
                                    currentStage = '手动发布'
                                    tools.PrintMsg("手动发布到${Tenv}环境","deploy")
                                     // 检查helm目录是否存在
                                    if (!fileExists("${WORKSPACE}/helm/Chart.yaml")) {
                                        error "🚨 Helm Chart目录不存在或Chart.yaml文件缺失"
                                    }
                                    // Helm部署逻辑
                                    // def chartName = "${imageName}-chart"
                                    def releaseName = "${imageName}-${Tenv}"
                                    
                                    // 打包Chart
                                    dir("${WORKSPACE}/helm") {
                                        // 动态更新Chart版本（示例：使用构建号）
                                        sh "sed -i 's/version: .*/version: ${BUILD_NUMBER}/' Chart.yaml"
                                        sh "/usr/local/bin/helm package . -d ${WORKSPACE}/ --version ${BUILD_NUMBER}"
                                        // sh "/usr/local/bin/helm repo add myrepo https://harbor.jdicity.local/chartrepo --username admin --password 'nRt87ccD&H*T%4WG' --ca-file /app/harbor.jdicity.local.crt"
                                        // sh "helm cm-push ${WORKSPACE}/${imageName}-${BUILD_NUMBER}.tgz myrepo --ca-file /usr/local/harbor.jdicity.local.crt"
                                          // 添加带认证的Helm仓库
                                        withCredentials([usernamePassword(
                                            credentialsId: 'HARBOR_ID', 
                                            usernameVariable: 'HARBOR_USER', 
                                            passwordVariable: 'HARBOR_PASSWORD'
                                        )]) {
                                            sh "helm repo remove ${releaseName} || true"
                                            sh """
                                                helm repo add ${releaseName} https://harbor.jdicity.local/chartrepo/myrepo --ca-file /usr/local/harbor.jdicity.local.crt \
                                                    --username ${HARBOR_USER} \
                                                    --password '${HARBOR_PASSWORD.replace("'", "'\\''")}' 
                                                
                                                helm cm-push ${WORKSPACE}/${imageName}-${BUILD_NUMBER}.tgz ${releaseName} \
                                                    --ca-file /usr/local/harbor.jdicity.local.crt \
                                                    --username ${HARBOR_USER} \
                                                    --password '${HARBOR_PASSWORD.replace("'", "'\\''")}'
                                            """
                                        }
                                    }
                                    k8sdeploy.HelmDeploy(
                                        this,
                                        "${Tenv}",
                                        "${releaseName}",
                                        "${releaseName}/${imageName}",
                                        "${k8s_ns}",
                                        [
                                            "image.repository": "${env.FULL_IMAGE_NAME}",
                                            "replicas": "${replicas}",
                                            "containerPort": "${containerPort}"
                                        ],
                                        "${BUILD_NUMBER}" 
                                    )
                                }
                            } else {
                                container('kubectl') {
                                    currentStage = '手动发布'
                                    tools.PrintMsg("手动发布到${Tenv}环境","deploy")
                                    k8sdeploy.Deploy(
                                        this,
                                        "${Tenv}",
                                        "${controllerType}",
                                        "${imageName}",
                                        "${env.FULL_IMAGE_NAME}",
                                        "${k8s_ns}"
                                    )
                                }
                            }
                        } else {
                            error "用户取消了手动发布"
                        }
                    }
                }
            }
        }
        stage("是否回滚"){
            when { expression { rollback } }  // 回滚时执行
            steps{
                script{
                    currentStage = '回滚'
                    if (deployMethod == "helm") {
                        container('helm') {
                            tools.PrintMsg("回滚到${Tenv}环境","rollback")
                            def releaseName = "${imageName}-${Tenv}"
                            withCredentials([usernamePassword(
                                credentialsId: 'HARBOR_ID', 
                                usernameVariable: 'HARBOR_USER', 
                                passwordVariable: 'HARBOR_PASSWORD'
                            )]) {
                                sh "helm repo remove ${releaseName} || true"
                                sh """
                                    helm repo add ${releaseName} https://harbor.jdicity.local/chartrepo/myrepo --ca-file /usr/local/harbor.jdicity.local.crt \
                                        --username ${HARBOR_USER} \
                                        --password '${HARBOR_PASSWORD.replace("'", "'\\''")}'
                                """
                            }
                            def rollbackStatus = k8sdeploy.HelmRollback(
                                this,
                                "${Tenv}",
                                releaseName,
                                "${k8s_ns}",
                                "${imageName}"
                            )
                            // 保存回滚信息
                            currentBuild.description = "Helm回滚: ${releaseName}"
                        }
                    } else {
                        container('kubectl') {
                            tools.PrintMsg("回滚到${Tenv}环境","rollback")
                            def rollbackImage = k8sdeploy.Rollback(
                                this,
                                "${Tenv}",
                                "${controllerType}",
                                "${imageName}",
                                "${k8s_ns}"
                            )
                            // 保存回滚镜像信息
                            env.FULL_IMAGE_NAME = rollbackImage
                            currentBuild.description = "${rollbackImage}"
                        }
                    }
                }
            }
        }
    }
    post {
        always {
            script {
                TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"))
                env.BUILD_TIME = new Date().format("yyyyMMdd_HHmmss")
                def buildTime = env.BUILD_TIME ?: "N/A"
                def buildDuration = currentBuild.durationString ?: "N/A"
                
                // 仅保留部署完成后的邮件发送逻辑
                if (currentStage in ['部署到k8s集群', '手动发布','回滚']) {
                    def deployType = (currentStage == '手动发布') ? '手动发布' : '自动发布'
                    toemail.Email(
                        currentBuild.currentResult,
                        "${env.emailUser}",
                        "${imageName}",
                        "${branch}",
                        "${env.BUILD_USER}",
                        buildTime,
                        buildDuration,
                        rollback,
                        "${k8s_ns}",
                        "CD阶段完成(${deployType}) - ${currentBuild.description}",
                        "${srcURL}"
                    )
                }
            }
        }
    }
}